{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "#!/usr/bin/python3\n",
    "# -*- coding: utf-8 -*-\n",
    "\n",
    "import os\n",
    "import sys\n",
    "import time\n",
    "import math\n",
    "import pandas as pd\n",
    "import numpy  as np\n",
    "from datetime import datetime, timedelta\n",
    "import traceback\n",
    "from utils.timecheck import ntp_client\n",
    "\n",
    "from api.asset     import cal_strategy_trade_usdt\n",
    "from api.position  import update_symbol_info, reset_leverage\n",
    "from api.market    import fetch_all_binance_swap_candle_data, fetch_binance_ticker_data\n",
    "from api.trade     import cal_order_amount, place_order, get_twap_symbol_info_list\n",
    "from utils.notification import send_msg_for_position, send_wechat_work_msg,send_dataframe\n",
    "\n",
    "from functions     import cal_factor, set_fundingrate,Select_coin\n",
    "from utils.commons import robust, sleep_until_run_time\n",
    "from rebalance.fee import replenish_bnb\n",
    "from config        import *\n",
    "\n",
    "#sys.stdout.reconfigure(encoding='utf-8')\n",
    "\n",
    "\n",
    "\n",
    "# ntp_client()\n",
    "# ====初始化\n",
    "quant.initialize()\n",
    "debug = True\n",
    "# ===设置默认最大杠杆数，变相增加资金容量\n",
    "\n",
    "\n",
    "#获取全策略的列表\n",
    "all_strategy_list = []\n",
    "for strategy_ in strategy_dic:\n",
    "    all_strategy_list += strategy_dic[strategy_]['strategy_list']\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'c_factor': '牛市动量nb策略_19',\n",
       "  'hold_period': '1H',\n",
       "  'type': '横截面',\n",
       "  'factors': [('纯手捏Mtm67', True, 19, 0, 1)],\n",
       "  'filters': [('斐波那契过滤', 12), ('斐波那契过滤空头', 12), ('涨跌幅max', 24)],\n",
       "  'filters_handle': {'before': 'f1_before_filter_fia12',\n",
       "   'after': 'default_handler'},\n",
       "  'long_weight': 1.5,\n",
       "  'short_weight': 0.5,\n",
       "  'select_coin_num': 1},\n",
       " {'c_factor': '牛市动量nb策略_20',\n",
       "  'hold_period': '1H',\n",
       "  'type': '横截面',\n",
       "  'factors': [('纯手捏Mtm67', True, 20, 0, 1)],\n",
       "  'filters': [('斐波那契过滤', 12), ('斐波那契过滤空头', 12), ('涨跌幅max', 24)],\n",
       "  'filters_handle': {'before': 'f1_before_filter_fia12',\n",
       "   'after': 'default_handler'},\n",
       "  'long_weight': 1.5,\n",
       "  'short_weight': 0.5,\n",
       "  'select_coin_num': 1},\n",
       " {'c_factor': '牛市动量nb策略_22',\n",
       "  'hold_period': '1H',\n",
       "  'type': '横截面',\n",
       "  'factors': [('纯手捏Mtm67', True, 22, 0, 1)],\n",
       "  'filters': [('斐波那契过滤', 12), ('斐波那契过滤空头', 12), ('涨跌幅max', 24)],\n",
       "  'filters_handle': {'before': 'f1_before_filter_fia12',\n",
       "   'after': 'default_handler'},\n",
       "  'long_weight': 1.5,\n",
       "  'short_weight': 0.5,\n",
       "  'select_coin_num': 1},\n",
       " {'c_factor': '牛市动量nb策略_24',\n",
       "  'hold_period': '1H',\n",
       "  'type': '横截面',\n",
       "  'factors': [('纯手捏Mtm67', True, 24, 0, 1)],\n",
       "  'filters': [('斐波那契过滤', 12), ('斐波那契过滤空头', 12), ('涨跌幅max', 24)],\n",
       "  'filters_handle': {'before': 'f1_before_filter_fia12',\n",
       "   'after': 'default_handler'},\n",
       "  'long_weight': 1.5,\n",
       "  'short_weight': 0.5,\n",
       "  'select_coin_num': 1},\n",
       " {'c_factor': '牛市动量nb策略_26',\n",
       "  'hold_period': '1H',\n",
       "  'type': '横截面',\n",
       "  'factors': [('纯手捏Mtm67', True, 26, 0, 1)],\n",
       "  'filters': [('斐波那契过滤', 12), ('斐波那契过滤空头', 12), ('涨跌幅max', 24)],\n",
       "  'filters_handle': {'before': 'f1_before_filter_fia12',\n",
       "   'after': 'default_handler'},\n",
       "  'long_weight': 1.5,\n",
       "  'short_weight': 0.5,\n",
       "  'select_coin_num': 1},\n",
       " {'c_factor': '牛市动量nb策略_28',\n",
       "  'hold_period': '1H',\n",
       "  'type': '横截面',\n",
       "  'factors': [('纯手捏Mtm67', True, 28, 0, 1)],\n",
       "  'filters': [('斐波那契过滤', 12), ('斐波那契过滤空头', 12), ('涨跌幅max', 24)],\n",
       "  'filters_handle': {'before': 'f1_before_filter_fia12',\n",
       "   'after': 'default_handler'},\n",
       "  'long_weight': 1.5,\n",
       "  'short_weight': 0.5,\n",
       "  'select_coin_num': 1},\n",
       " {'c_factor': '牛市动量nb策略_30',\n",
       "  'hold_period': '1H',\n",
       "  'type': '横截面',\n",
       "  'factors': [('纯手捏Mtm67', True, 30, 0, 1)],\n",
       "  'filters': [('斐波那契过滤', 12), ('斐波那契过滤空头', 12), ('涨跌幅max', 24)],\n",
       "  'filters_handle': {'before': 'f1_before_filter_fia12',\n",
       "   'after': 'default_handler'},\n",
       "  'long_weight': 1.5,\n",
       "  'short_weight': 0.5,\n",
       "  'select_coin_num': 1},\n",
       " {'c_factor': '牛市动量nb策略_32',\n",
       "  'hold_period': '1H',\n",
       "  'type': '横截面',\n",
       "  'factors': [('纯手捏Mtm67', True, 32, 0, 1)],\n",
       "  'filters': [('斐波那契过滤', 12), ('斐波那契过滤空头', 12), ('涨跌幅max', 24)],\n",
       "  'filters_handle': {'before': 'f1_before_filter_fia12',\n",
       "   'after': 'default_handler'},\n",
       "  'long_weight': 1.5,\n",
       "  'short_weight': 0.5,\n",
       "  'select_coin_num': 1},\n",
       " {'c_factor': '牛市动量nb策略_34',\n",
       "  'hold_period': '1H',\n",
       "  'type': '横截面',\n",
       "  'factors': [('纯手捏Mtm67', True, 34, 0, 1)],\n",
       "  'filters': [('斐波那契过滤', 12), ('斐波那契过滤空头', 12), ('涨跌幅max', 24)],\n",
       "  'filters_handle': {'before': 'f1_before_filter_fia12',\n",
       "   'after': 'default_handler'},\n",
       "  'long_weight': 1.5,\n",
       "  'short_weight': 0.5,\n",
       "  'select_coin_num': 1},\n",
       " {'c_factor': '牛市动量nb策略_36',\n",
       "  'hold_period': '1H',\n",
       "  'type': '横截面',\n",
       "  'factors': [('纯手捏Mtm67', True, 36, 0, 1)],\n",
       "  'filters': [('斐波那契过滤', 12), ('斐波那契过滤空头', 12), ('涨跌幅max', 24)],\n",
       "  'filters_handle': {'before': 'f1_before_filter_fia12',\n",
       "   'after': 'default_handler'},\n",
       "  'long_weight': 1.5,\n",
       "  'short_weight': 0.5,\n",
       "  'select_coin_num': 1},\n",
       " {'c_factor': '牛市动量nb策略_38',\n",
       "  'hold_period': '1H',\n",
       "  'type': '横截面',\n",
       "  'factors': [('纯手捏Mtm67', True, 38, 0, 1)],\n",
       "  'filters': [('斐波那契过滤', 12), ('斐波那契过滤空头', 12), ('涨跌幅max', 24)],\n",
       "  'filters_handle': {'before': 'f1_before_filter_fia12',\n",
       "   'after': 'default_handler'},\n",
       "  'long_weight': 1.5,\n",
       "  'short_weight': 0.5,\n",
       "  'select_coin_num': 1},\n",
       " {'c_factor': '赛博狗2',\n",
       "  'hold_period': '24H',\n",
       "  'type': '横截面',\n",
       "  'factors': [('赛博狗2', True, 2160, 0, 1)],\n",
       "  'filters': [],\n",
       "  'filters_handle': {'before': 'default_handler', 'after': 'default_handler'},\n",
       "  'long_weight': 1,\n",
       "  'short_weight': 1,\n",
       "  'select_coin_num': 10}]"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "all_strategy_list"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "# ===加载市场信息\n",
    "quant.load_market()\n",
    "# =====设置参数\n",
    "exchange        \t = quant.exchange\n",
    "symbol_list     \t = quant.symbol_list\n",
    "min_qty         \t = quant.min_qty\n",
    "price_precision \t = quant.price_precision\n",
    "min_notional  \t\t = quant.min_notional\n",
    "njob1           \t = quant.njob1\n",
    "njob2           \t = quant.njob2\n",
    "trade_ratio     \t = quant.trade_ratio\n",
    "strategy_list   \t = all_strategy_list\n",
    "min_kline_size  \t = quant.min_kline_size\n",
    "max_one_order_amount = quant.max_one_order_amount\n",
    "twap_interval        = quant.twap_interval\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<config.QuantConfig at 0x7fef39dc9400>"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "quant"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "获取所有币种K线数据完成，花费时间： 128.04890608787537\n",
      "保存资金数据完成，花费时间： 0.2875661849975586\n",
      "no enough data MYROUSDT\n",
      "========================实例化计算因子中========================\n",
      "back_hour_list: [24, 48, 72, 96, 120, 144, 168, 336, 504, 720, 1440, 2160]\n",
      "dataset_dates: ['2021-01-01', '2023-09-30', '2023-10-01', '2023-11-01']\n",
      "model_path: /home/admin/多策略多账户/src_product_多/factors/赛博狗2.py.pkl\n",
      "hyper_paras: {'learning_rate': 0.01, 'max_depth': 15, 'num_leaves': 661, 'min_data_in_leaf': 22}\n",
      "filter_list: []\n",
      "suggest_hold_hour: 24\n",
      "================================================================\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Exception ignored in: <function Booster.__del__ at 0x7fef0e5021f0>\n",
      "Traceback (most recent call last):\n",
      "  File \"/opt/src/miniconda3/envs/py38/lib/python3.8/site-packages/lightgbm/basic.py\", line 2657, in __del__\n",
      "    try:\n",
      "KeyboardInterrupt: \n"
     ]
    }
   ],
   "source": [
    "\n",
    "# =====sleep直到下一个整点小时\n",
    "if debug:\n",
    "    run_time = datetime.strptime('2024-03-07 01:20:00', \"%Y-%m-%d %H:%M:%S\")\n",
    "    #run_time = sleep_until_run_time('1h', if_sleep=False, cheat_seconds=0)\n",
    "else:\n",
    "    run_time = sleep_until_run_time('1h', if_sleep=True,  cheat_seconds=0)\n",
    "\n",
    "now = datetime.now()\n",
    "# =====合约每日结算时api暂停1分钟\n",
    "if (now.hour % 8 == 0 and now.minute == 0):\n",
    "    print('每日结算时间')\n",
    "    time.sleep(60 - now.second)\n",
    "\n",
    "# =====并行获取所有币种的1小时K线\n",
    "s_time = time.time()\n",
    "symbol_candle_data = fetch_all_binance_swap_candle_data(exchange, symbol_list, run_time, njob1)\n",
    "print('获取所有币种K线数据完成，花费时间：', time.time() - s_time)\n",
    "\n",
    "# =====获取当前资金费率\n",
    "s_time = time.time()\n",
    "set_fundingrate(exchange)\n",
    "print('保存资金数据完成，花费时间：', time.time() - s_time)\n",
    "\n",
    "# =====选币数据整理 & 选币\n",
    "#计算因子\n",
    "s_time = time.time()\n",
    "alldata = cal_factor(\n",
    "    symbol_candle_data, strategy_list, run_time, njob2, min_kline_size=min_kline_size\n",
    ")\n",
    "print('完成选币数据整理，花费时间：', time.time() - s_time)\n",
    "\n",
    "### 遍历账号，下单\n",
    "for strategy_ in strategy_dic:\n",
    "    print(strategy_)\n",
    "    #初始化quant\n",
    "    apiKey = strategy_dic[strategy_]['apiKey']\n",
    "    secret = strategy_dic[strategy_]['secret']\n",
    "    strategy_list = strategy_dic[strategy_]['strategy_list']\n",
    "    trade_ratio = strategy_dic[strategy_]['trade_ratio']\n",
    "    quant_ = QuantConfig(apiKey, secret, proxy, njob1, njob2, trade_ratio, min_kline_size, black_list,\n",
    "                        max_one_order_amount, twap_interval, strategy_list, debug=Debug)\n",
    "    quant_.initialize()\n",
    "    exchange = quant_.exchange\n",
    "    strategy_list = quant_.strategy_list\n",
    "\n",
    "    #####################\n",
    "    # 获取U本位合约账户净值(不包含未实现盈亏)\n",
    "    if debug:\n",
    "        # 测试计算\n",
    "        # equity = 1000\n",
    "        # 真实账户\n",
    "        balance    = robust(exchange.fapiPrivateV2_get_balance, func_name='fapiPrivateV2_get_balance')  # 获取账户净值\n",
    "        balance    = pd.DataFrame(balance)\n",
    "        equity     = float(balance[balance['asset'] == 'USDT']['balance'])\n",
    "        equity_unrealized = float(balance[balance['asset'] == 'USDT']['crossUnPnl'])\n",
    "\n",
    "    else:\n",
    "        balance    = robust(exchange.fapiPrivateV2_get_balance, func_name='fapiPrivateV2_get_balance')  # 获取账户净值\n",
    "        balance    = pd.DataFrame(balance)\n",
    "        equity     = float(balance[balance['asset'] == 'USDT']['balance'])\n",
    "        equity_unrealized = float(balance[balance['asset'] == 'USDT']['crossUnPnl'])\n",
    "\n",
    "    trade_usdt = (equity+equity_unrealized)*trade_ratio\n",
    "    print('账户净值:', (equity+equity_unrealized), '杠杆:', trade_ratio, '实际净值:', trade_usdt)\n",
    "    send_wechat_work_msg(f\"账户净值: {equity+equity_unrealized}美元,加完杠杆后的资金量 {trade_usdt}美元!\")\n",
    "    #trade_usdt = equity*trade_ratio\n",
    "    #print('账户净值:', equity, '杠杆:', trade_ratio, '实际净值:', trade_usdt)\n",
    "    # =====获取每个策略分配的资金：固定资金，之后的版本会改成浮动\n",
    "    strategy_trade_usdt = cal_strategy_trade_usdt(strategy_list, trade_usdt)\n",
    "    # =====获取账户的实际持仓\n",
    "    if debug:\n",
    "        # symbol_info = pd.DataFrame(index=symbol_list, columns=['当前持仓量'])\n",
    "        # symbol_info['当前持仓量'] = 0\n",
    "         symbol_info = update_symbol_info(exchange, symbol_list)\n",
    "    else:\n",
    "        symbol_info = update_symbol_info(exchange, symbol_list)\n",
    "    #\n",
    "    dfsendtowechat=symbol_info[symbol_info[\"当前持仓量\"]!=0] #正负持仓\n",
    "    send_dataframe(dfsendtowechat)\n",
    "    # =====开始计算&下单\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
